package com.piece.module.spider.context;

import com.piece.core.framework.util.file.FileUtil;
import com.piece.module.spider.support.SpiderOutput;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SpiderJobContext extends SpiderContext {

	private List<SpiderOutput> outputs = new ArrayList<>();

	private OutputStream outputstream;

	private boolean output;

	public SpiderJobContext(OutputStream outputstream, boolean output) {
		super();
		this.outputstream = outputstream;
		this.output = output;
	}

	public void close(){
		try {
			this.outputstream.close();
		} catch (Exception e) {
		}
	}

	@Override
	public void addOutput(SpiderOutput output) {
		if(this.output){
			synchronized (this.outputs){
				this.outputs.add(output);
			}
		}
	}

	@Override
	public List<SpiderOutput> getOutputs() {
		return outputs;
	}

	public OutputStream getOutputstream() {
		return this.outputstream;
	}

	public static SpiderJobContext create(String directory, String id, String logId, boolean output) {
		OutputStream os;
		try {
			String path = FileUtil.getStoragePath(directory + File.separator + id + File.separator + "logs");
			String storePathAndName = path + File.separator + logId + ".log";
			FileUtil.writeByteArrayToFile(new File(storePathAndName), new byte[]{});
			File file = new File(storePathAndName);
			os = new FileOutputStream(file, true);
			SpiderJobContext context = new SpiderJobContext(os, output);
			context.setFlowId(id);
			return context;
		} catch (Exception e) {
			log.error("创建爬虫日志文件出错：{}", e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
	}
}
